package com.ct.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.ct.entity.enums.AdvanceApprovalEnum;
import com.ct.entity.enums.PageSize;
import com.ct.entity.po.AdvanceApproval;
import com.ct.entity.po.Approval;
import com.ct.entity.po.Travel;
import com.ct.entity.po.User;
import com.ct.entity.query.AdvanceApprovalQuery;
import com.ct.entity.query.ApprovalQuery;
import com.ct.entity.query.SimplePage;
import com.ct.entity.vo.PaginationResultVO;
import com.ct.entity.vo.TravelVO;
import com.ct.mappers.AdvanceApprovalMapper;
import com.ct.mappers.ApprovalMapper;
import com.ct.service.AdvanceApprovalService;
import com.ct.service.client.TravelClient;
import com.ct.service.client.UserClient;
import com.ct.utils.CopyTools;
import com.ct.utils.StringTools;

import jakarta.annotation.Resource;

/**
 * 财务人员审批预支款记录 业务接口实现
 */
@Service("advanceApprovalService")
public class AdvanceApprovalServiceImpl implements AdvanceApprovalService {

    @Resource
    private AdvanceApprovalMapper<AdvanceApproval, AdvanceApprovalQuery> advanceApprovalMapper;

    @Resource
    private TravelClient travelClient;

    @Resource
    private UserClient userClient;

    @Resource
    private ApprovalMapper<Approval, ApprovalQuery> approvalMapper;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<AdvanceApproval> findListByParam(AdvanceApprovalQuery param) {
        return this.advanceApprovalMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(AdvanceApprovalQuery param) {
        return this.advanceApprovalMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<AdvanceApproval> findListByPage(AdvanceApprovalQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<AdvanceApproval> list = this.findListByParam(param);
        PaginationResultVO<AdvanceApproval> result = new PaginationResultVO<>(count, page.getPageSize(),
                page.getPageNo(),
                page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(AdvanceApproval bean) {
        return this.advanceApprovalMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<AdvanceApproval> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.advanceApprovalMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<AdvanceApproval> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.advanceApprovalMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(AdvanceApproval bean, AdvanceApprovalQuery param) {
        StringTools.checkParam(param);
        return this.advanceApprovalMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(AdvanceApprovalQuery param) {
        StringTools.checkParam(param);
        return this.advanceApprovalMapper.deleteByParam(param);
    }

    /**
     * 根据AdvanceApprovalId获取对象
     */
    @Override
    public AdvanceApproval getAdvanceApprovalByAdvanceApprovalId(Integer advanceApprovalId) {
        return this.advanceApprovalMapper.selectByAdvanceApprovalId(advanceApprovalId);
    }

    /**
     * 根据AdvanceApprovalId修改
     */
    @Override
    public Integer updateAdvanceApprovalByAdvanceApprovalId(AdvanceApproval bean, Integer advanceApprovalId) {
        return this.advanceApprovalMapper.updateByAdvanceApprovalId(bean, advanceApprovalId);
    }

    /**
     * 根据AdvanceApprovalId删除
     */
    @Override
    public Integer deleteAdvanceApprovalByAdvanceApprovalId(Integer advanceApprovalId) {
        return this.advanceApprovalMapper.deleteByAdvanceApprovalId(advanceApprovalId);
    }

    @Override
    public PaginationResultVO<TravelVO> getApproveAdvanceRecord(String userId, Integer pageNo, Integer pageSize) {
        AdvanceApprovalQuery advanceApprovalQuery = new AdvanceApprovalQuery();
        advanceApprovalQuery.setFinanceId(userId);
        List<AdvanceApproval> advanceApprovalList = this.findListByParam(advanceApprovalQuery);
        Map<Integer, AdvanceApproval> advanceApprovalMap = advanceApprovalList.stream()
                .collect(Collectors.toMap(AdvanceApproval::getAdvanceId, advanceApproval -> advanceApproval));

        if (advanceApprovalList.isEmpty()) {
            return null;
        }

        // 获取出差申请信息
        List<Integer> travelIdList = advanceApprovalList.stream().map(AdvanceApproval::getAdvanceId).distinct()
                .toList();
        List<Travel> travelList = this.travelClient.getAllTravelsByIdList(travelIdList);

        // 获取出差申请人信息
        List<String> userIdList = travelList.stream().map(Travel::getUserId).distinct().toList();
        List<User> userList = userClient.getAllUsersByIdList(userIdList);
        Map<String, User> userMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, user -> user));

        List<TravelVO> travelVOList = new ArrayList<>();
        for (Travel travel : travelList) {
            TravelVO travelVO = CopyTools.copy(travel, TravelVO.class);

            AdvanceApproval advanceApproval = advanceApprovalMap.get(travel.getTravelId());
            travelVO.setPayment(advanceApproval.getPayment());

            ApprovalQuery approvalQuery = new ApprovalQuery();
            approvalQuery.setTravelId(travel.getTravelId());
            Approval approval = approvalMapper.selectList(approvalQuery).get(0);

            travelVO.setAdvanceRejection(approval.getAdvanceRejection());
            travelVO.setApprovalId(approval.getApprovalId());

            travelVO.setAdvanceStatus(approval.getAdvanceApproval().toString());
            travelVO.setAdvanceStatusName(AdvanceApprovalEnum.getByType(approval.getAdvanceApproval()).getDesc());

            User user = userMap.get(travel.getUserId());
            travelVO.setUserName(user.getName());
            travelVO.setUserPhone(user.getPhone());
            travelVO.setUserEmail(user.getEmail());
            travelVO.setPosition(user.getPosition());
            travelVO.setBudget(travelVO.getFoodCost().add(travelVO.getHotelCost()).add(travelVO.getTransportCost()));

            travelVOList.add(travelVO);
        }

        int count = travelVOList.size();
        int start = (pageNo - 1) * pageSize;
        int end = start + pageSize;
        if (end > count) {
            end = count;
        }
        int totalPage = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;

        PaginationResultVO<TravelVO> result = new PaginationResultVO<>(count, pageSize, pageNo, totalPage,
                travelVOList);

        return result;
    }

    @Override
    public AdvanceApproval getAdvanceApprovalByAdvanceId(Integer advanceId) {
        return this.advanceApprovalMapper.selectByAdvanceId(advanceId);
    }

    /*
     * @KafkaListener(topics = "advance-approval-topic", groupId =
     * "advance-approval-group")
     * public void receiveMessage(String message) {
     * System.out.println("收到消息：" + message);
     * }
     */

}